package cn.mulanbay.api.system.config;

import cn.mulanbay.common.config.Constants;
import cn.mulanbay.common.util.DESUtil;
import cn.mulanbay.common.util.StringUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

/**
 * Feign客户端调用安全配置
 *
 * @author fenghong
 * @create 2022-01-16 10:00
 */
public class FeignRequestInterceptor implements RequestInterceptor {

    private static final Logger log = LoggerFactory.getLogger(FeignRequestInterceptor.class);

    /**
     * 加密秘钥
     */
    @Value("${security.password.salt:12345678}")
    String pwdKey;

    /**
     * 密码
     */
    @Value("${security.feign.password:111222}")
    String pwd;

    public FeignRequestInterceptor() {
        log.info("init FeignRequestInterceptor,pwdKey:"+pwdKey+",pwd:"+pwd);
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String url = requestTemplate.url();
        log.debug("url:"+url+",set feign auth,pwdKey:"+pwdKey+",pwd:"+pwd);
        if(StringUtil.isEmpty(pwdKey)){
            log.warn("set feign auth 未找到pwdKey");
            return;
        }
        try {
            String authInfo = pwd+","+ System.currentTimeMillis();
            String ep = DESUtil.encrypt(authInfo,pwdKey);
            requestTemplate.header(Constants.FEIGN_AUTH_HEADER, ep);
        } catch (Exception e) {
            log.error("set feign auth error",e);
        }
    }

}
